<template>
  <div class="comment-form">
    <a-textarea
      v-model:value="content"
      placeholder="请输入评论内容..."
      :rows="3"
      class="comment-input"
    />
    <div class="form-actions mt-2">
      <a-button
        v-if="showCancel"
        type="primary"
        @click="handleCancel"
        style="background:green  "
      >
        取消
      </a-button>
      <a-button
        type="primary"
        @click="handleSubmit"
        :loading="submitting"

      >
        发布
      </a-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { publishCommentUsingPost} from '@/api/commentController.ts';

// 接收的props
const props = defineProps({
  targetId: {
    type: Number,
    required: true
  },
  targetType: {
    type: Number,
    required: true
  },
  parentId: {
    type: Number,
    default: 0
  },
  currentUserId: {
    type: Number,
    required: true
  },
  showCancel: {
    type: Boolean,
    default: true
  }
});

// 评论内容
const content = ref('');
// 提交状态
const submitting = ref(false);

// 处理提交
const handleSubmit = computed(()=>async () => {
  if (!content.value.trim()) {
    // 可以添加提示信息
    return;
  }

  try {
    submitting.value = true;

    const commentRequest = {
      userId: props.currentUserId,
      content: content.value.trim(),
      targetId: props.targetId,
      targetType: props.targetType,
      parentId: props.parentId
    };

    const response = await publishCommentUsingPost(commentRequest);
    // 触发成功事件
    emit('on-comment-success', response.data);
    // 清空输入框
    content.value = '';
  } catch (error) {
    console.error('发布评论失败:', error);
  } finally {
    submitting.value = false;
  }})

// 处理取消
const handleCancel = () => {
  content.value = '';
  emit('on-cancel');
};

// 定义emit事件
const emit = defineEmits(['on-comment-success', 'on-cancel']);
</script>

<style scoped>
.comment-form {
  width: 100%;
}

.comment-input {
  width: 100%;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 8px;
}
</style>
